package com.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.CodeMsg;
import com.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取session
        HttpSession session = request.getSession(true);
        // 判断用户是否存在，不存在就跳转到登录界面
        if(session.getAttribute("user") == null){

            Result r = Result.error(CodeMsg.SESSION_TIMOUT);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");

            PrintWriter pw = response.getWriter();
            ObjectMapper om = new ObjectMapper();
            String json = om.writeValueAsString(r);
            pw.write(json);
            return false;
        }else{

            return true;
        }
    }
}